﻿package com.snakedickgames.common.rendering2D 
{
    import com.pblabs.engine.PBE;
    import com.pblabs.engine.debug.Logger;
    import com.pblabs.engine.core.ObjectType;
    import com.pblabs.rendering2D.DisplayObjectRenderer;
    import flash.display.Sprite;
    import flash.geom.Point;
    /**
     * Stack multiple DisplayObjectRenderers.  Helps for proper draw order.
     * 
     */
    public class CompositeRenderer extends DisplayObjectRenderer
    {
        public var renderers:Array = new Array();
        
        public function CompositeRenderer() 
        {
            super();
            _displayObject = new Sprite();
        }
        
        override protected function onReset():void 
        {
            super.onReset();
        
            // nothing to do?
            if (initComplete || !renderersRegistered())
                return;
                
            for (var i:* in renderers)
            {
                var renderer:DisplayObjectRenderer = renderers[i];
                (_displayObject as Sprite).addChild(renderer.displayObject)
                // Setup the type mask to include all children
                if (!objectMask)
                    objectMask = new ObjectType();
                if (renderer.objectMask)
                {
                    for (var j:String in renderer.objectMask.typeNames)
                    {
                        objectMask.add(renderer.objectMask.typeNames[j]);
                    }
                }
            }
            initComplete = true;
        }
        
        public function removeRenderer(renderer:DisplayObjectRenderer):void
        {    
            // TODO: remove type mask?
            (displayObject as Sprite).removeChild(renderer.displayObject);
        }
        
        protected function renderersRegistered():Boolean
        {
            for (var r:* in renderers)
            {
                var renderer:DisplayObjectRenderer = renderers[r];
                if (!renderer.isRegistered)
                    return false;
            }
            return true;
        }
        
        override public function pointOccupied(worldPosition:Point, mask:ObjectType = null):Boolean 
        {
            for (var i:* in renderers)
            {
                var renderer:DisplayObjectRenderer = renderers[i];
                if (PBE.objectTypeManager.doTypesOverlap(mask, renderer.objectMask))
                    if (renderer.pointOccupied(worldPosition))
                        return true;
            }
            return false;
        }
        
        protected var initComplete:Boolean = false;
    }

}